<?php

namespace ApiBundle\Controller;

use AdminBundle\Entity\BaseWebchatUser;
use AdminBundle\Entity\BaseWebchatUserExtra;
use AdminBundle\Services\CacheTask;
use AdminBundle\Task\ContactUploadTask;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class HeartbeatController extends BaseController
{
    private $device;

    /**
     * client heartbead request and get tasks.
     *
     * @Route(path="/task", name="api_heartbeat")
     * @Method({"GET", "POST"})
     */
    public function indexAction(Request $request)
    {
        // 返回结果参数
        $result = [];

        // 获取JSON包
        $data_template = [
            'device' => ['imei' => '', 'free_disk' => 0],
            'wechat' => ['username' => '', 'status' => 0]
        ];
        $data = $this->apiRequest($request, $data_template);

        $device = $data['device'];
        $wechat = $data['wechat'];

        if (empty($wechat['username'])) {
            return $this->apiJson(Response::HTTP_NOT_FOUND, '微信用户名为空.', $result);
        }

        if ($this->getDevice($device['imei']) == null) {
            // 微信状态异常
            return $this->apiJson(Response::HTTP_NOT_FOUND, '终端不存在,请初始化.', $result);
        }

        // 新增加微信用户
        $newWechat = $this->wechatNew($wechat);

        switch ($wechat['status']) {
            case 1:
                // 封号:服务端更新状态
                break;
            case 2:
                // 重新验证:下发用户名和密码,重新登录
                $result['task'] = $this->twiceAuthenticate($wechat['username']);
                break;
            case 0:
            default:
                // 正常状态
                $result['task'] = $this->getApiTask($device['imei'], $wechat['username']);
                if ($newWechat) {
                    $contactUploadTask = new ContactUploadTask();
                    $result['task'][] = $contactUploadTask->jsonTask();
                }
                break;
        }

        // 成功返回
        return $this->apiJson(0, '', $result);
    }

    private function getDevice($imei)
    {
        $em = $this->getDoctrine()->getManager();

        $this->device = $em->getRepository('AdminBundle:BaseDevice')->findOneBy(['imei' => $imei]);
        return $this->device;
    }

    /**
     * 新增微信号用户
     * @param $wechat
     * @return bool
     */
    private function wechatNew(&$wechat)
    {
        $em = $this->getDoctrine()->getManager();
        $baseWebchatUser = $em->getRepository('AdminBundle:BaseWebchatUser')
            ->findOneBy(['userName' => $wechat['username']]);
        if ($baseWebchatUser != null) {
            return false;
        }
        $baseWebchatUser = new BaseWebchatUser();
        $baseWebchatUser->setCtime(new \DateTime())
            ->setIp($this->ip)
            ->setCreator($this->username)
            ->setUserName($wechat['username'])
            ->setDeviceId($this->device->getId())
            ->setDeviceImei($this->device->getImei())
            ->setDeviceText($this->device->getName());

        $em->persist($baseWebchatUser);
        $em->flush();

        $baseWebchatUserExtra = new BaseWebchatUserExtra();
        $baseWebchatUserExtra->setId($baseWebchatUser->getId())
            ->setLastRequestTime(new \DateTime())
            ->setLastReportTime(new \DateTime())
            ->setLastRequestIp($this->ip)
            ->setStatus($wechat['status']);

        $em->persist($baseWebchatUserExtra);
        $em->flush();
        return true;
    }

    /**
     * 格式化任务
     * @param $id
     * @param $name
     * @param $uri
     * @param $method
     * @param $action
     * @param $param
     * @return array
     */
    private function taskPackage($id, $name, $uri, $param = [], $method = '', $action = '')
    {
        $task = ['id' => $id, 'name' => $name, 'uri' => $uri, 'method' => $method,
            'action' => $action, 'params' => $param];
        return $task;
    }

    /**
     * 重新验证:下发用户名和密码,重新登录
     * @param $username
     * @return array
     */
    private function twiceAuthenticate($username)
    {
        $data = [];
        $baseWebchatUser = $this->getDoctrine()->getRepository('AdminBundle:BaseWebchatUser')
            ->findOneBy(['userName' => $username]);
        if ($baseWebchatUser != null) {
            $data[] = $this->taskPackage(0, '重新登录', 'login',
                ['username' => $username, 'password' => $baseWebchatUser->getPassword()]);
        }

        return $data;
    }

    /**
     * 根据设备ID，微信号，获取要执行的任务.
     * @param $imei
     * @param $username
     * @return array
     */
    private function getApiTask($imei, $username)
    {
        // cache hit
        $config = $this->getParameter('redis');
        $cacheTask = CacheTask::getInstance($config);
        $jsonTask = $cacheTask->taskByUserName($username);
        $data = [];
        foreach ($jsonTask as $task) {
            $list = json_decode($task, true);
            $data[] = $list;
//            $data[intval($list['id'])] = $list;
        }
        sort($data);
        return $data;

        // database hit
        $em = $this->getDoctrine()->getManager();
        $taskQueueWaitings = $em->getRepository('AdminBundle:TaskQueueWaiting')
            ->fetchTaskByUserName($username);
        if ($taskQueueWaitings == null)
            return [];
        $data = [];
        foreach ($taskQueueWaitings as $taskQueueWaiting) {
            $data[] = $this->taskPackage(
                $taskQueueWaiting['id'],
                $taskQueueWaiting['name'],
                $taskQueueWaiting['uri'],
                json_decode($taskQueueWaiting['params'], true)
            );
        }
        // todo: 删除已经分配的任务
//        $em->getRepository('AdminBundle:TaskQueueWaiting')->deleteDelivery($id);
        return $data;

    }

    /**
     * 返回协议DEMO
     * @return array
     */
    private function demoProtocal()
    {
        $data[] = $this->taskPackage(0, '添加好友', 'WXAddFriendTask', [
            'sourceType' => '3',// 0:扫一扫, 1:搜索微信号, 2:搜索手机号, 3:通讯录
            'helloMsg' => '最近好吗',
            'delay' => 3,
            'index' => 0,
            'friends' => [
                '13911968643',
                '18612300348'
            ]
        ]);
        return $data;

        $data[] = $this->taskPackage(0, '上报粉丝信息', 'WXUploadFriendsInfoTask');
        $data[] = $this->taskPackage(1, '熟人聊天任务', 'WXChatToContactTask', [
            [
                'nickname' => '赖泓宇', 'username' => 'wxid_109fsxsirl8122', 'mobile' => '', 'message' =>
                [
                    ['type' => 'text', 'value' => '你好啊，测试.', 'delay' => 0],
                    ['type' => 'image', 'value' => 'http://admin.bjtwtx.com/upload/2017/09/14/326ffed0e275c55c4a8f34ab8b037293.jpeg', 'delay' => 0],
                ]
            ],
            [
                'nickname' => '望月', 'username' => 'wxid_gnxtfbfx6nbs12', 'mobile' => '', 'message' =>
                [
                    ['type' => 'text', 'value' => '你好啊，测试.', 'delay' => 0],
                    ['type' => 'image', 'value' => 'http://admin.bjtwtx.com/upload/2017/09/14/326ffed0e275c55c4a8f34ab8b037293.jpeg', 'delay' => 0],
                ]
            ]
        ]);
        $data[] = $this->taskPackage(0, '朋友圈浏览', 'WXMoments');
        $data[] = $this->taskPackage(0, '游戏浏览', 'WXGames');
        $data[] = $this->taskPackage(0, '电商', 'WXShopping');
        $data[] = $this->taskPackage(0, '生活', 'WXWallet');
        $data[] = $this->taskPackage(0, '公众号', 'WXOfficialAccounts', [
            ['name' => '红漫画', 'id' => 'gh_a2e622bfd7cc'],
            ['name' => '游戏码农', 'id' => 'gh_61c9d1729170'],
        ]);
        $data[] = $this->taskPackage(0, '发朋友圈', 'WXTimeLineTask', [
            'content' => '今天天气真好.',
            'images' => ['http://admin.bjtwtx.com/upload/2017/09/14/326ffed0e275c55c4a8f34ab8b037293.jpeg'],
            'comment' => '出来约吗',
            'like' => true,
            'type' => 'mixed'
        ]);

        return $data;
    }
}
